import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.List;

public class GradeExamFrame extends JFrame {
    private int examId;
    private User teacher;
    private Exam exam;
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private JButton gradeButton;
    private JButton refreshButton;
    private JButton closeButton;
    private ExamDAO examDAO;
    private ExamRecordDAO examRecordDAO;
    private UserDAO userDAO;

    public GradeExamFrame(int examId, User teacher) {
        this.examId = examId;
        this.teacher = teacher;
        this.examDAO = new ExamDAO();
        this.examRecordDAO = new ExamRecordDAO();
        this.userDAO = new UserDAO();

        // 获取考试信息
        this.exam = examDAO.getExamById(examId);

        initComponents();
        setupLayout();
        setupEvents();
        loadStudentList();
    }

    private void initComponents() {
        setTitle("阅卷 - " + (exam != null ? exam.getTitle() : "考试"));
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(900, 600);
        setLocationRelativeTo(null);

        // 表格列名
        String[] columnNames = { "学生ID", "学生姓名", "开始时间", "提交时间", "状态", "得分", "操作" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        studentTable = new JTable(tableModel);
        studentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        studentTable.setRowHeight(25);

        gradeButton = new JButton("阅卷");
        refreshButton = new JButton("刷新");
        closeButton = new JButton("关闭");
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(70, 130, 180));
        topPanel.setPreferredSize(new Dimension(900, 60));

        JLabel titleLabel = new JLabel("阅卷管理", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setForeground(Color.WHITE);

        JPanel infoPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        infoPanel.setBackground(new Color(70, 130, 180));
        if (exam != null) {
            JLabel examLabel = new JLabel("考试: " + exam.getTitle());
            examLabel.setForeground(Color.WHITE);
            infoPanel.add(examLabel);
        }

        topPanel.add(titleLabel, BorderLayout.CENTER);
        topPanel.add(infoPanel, BorderLayout.EAST);

        // 中间表格面板
        JScrollPane scrollPane = new JScrollPane(studentTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder("参考学生列表"));

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(gradeButton);
        buttonPanel.add(refreshButton);
        buttonPanel.add(closeButton);

        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void setupEvents() {
        gradeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                gradeSelectedStudent();
            }
        });

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadStudentList();
            }
        });

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        // 双击查看试卷
        studentTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    viewStudentPaper();
                }
            }
        });
    }

    private void loadStudentList() {
        tableModel.setRowCount(0);
        List<ExamRecord> records = examRecordDAO.getExamRecordsByExam(examId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        for (ExamRecord record : records) {
            User student = userDAO.getUserById(record.getStudentId());
            if (student != null) {
                String startTime = record.getStartTime() != null ? sdf.format(record.getStartTime()) : "未开始";
                String submitTime = record.getSubmitTime() != null ? sdf.format(record.getSubmitTime()) : "未提交";
                String status = getStatusText(record.getStatus());
                String score = record.getTotalScore() > 0 ? String.valueOf(record.getTotalScore()) : "未评分";

                Object[] row = {
                        record.getStudentId(),
                        student.getRealName(),
                        startTime,
                        submitTime,
                        status,
                        score,
                        "阅卷"
                };
                tableModel.addRow(row);
            }
        }
    }

    private String getStatusText(String status) {
        switch (status) {
            case "not_started":
                return "未开始";
            case "in_progress":
                return "进行中";
            case "submitted":
                return "已提交";
            case "graded":
                return "已阅卷";
            default:
                return status;
        }
    }

    private void viewStudentPaper() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个学生！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int studentId = (Integer) tableModel.getValueAt(selectedRow, 0);
        String status = (String) tableModel.getValueAt(selectedRow, 4);

        if (!"已提交".equals(status) && !"已阅卷".equals(status)) {
            JOptionPane.showMessageDialog(this, "该学生还未提交考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 打开试卷查看界面
        new ExamPaperViewFrame(examId, studentId, teacher).setVisible(true);
    }

    private void gradeSelectedStudent() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个学生！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int studentId = (Integer) tableModel.getValueAt(selectedRow, 0);
        String status = (String) tableModel.getValueAt(selectedRow, 4);

        if (!"已提交".equals(status) && !"已阅卷".equals(status)) {
            JOptionPane.showMessageDialog(this, "该学生还未提交考试！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 打开详细阅卷界面
        DetailedGradingFrame gradingFrame = new DetailedGradingFrame(examId, studentId, teacher);
        gradingFrame.setVisible(true);

        // 当阅卷窗口关闭后刷新列表
        gradingFrame.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosed(java.awt.event.WindowEvent e) {
                loadStudentList(); // 刷新学生列表
            }
        });
    }
}